package cn.stronglink.netrequest.util;

import android.os.Environment;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import cn.stronglink.netrequest.exceptions.BusinessErrorException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Tgb on 2018/6/4.
 */

public class HttpUtil {

    public static final MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json; charset=utf-8");
    private static int CONNECT_TIME_OUT = 1;
    private static int READ_TIME_OUT = 1;
    private static int WRITE_TIME_OUT = 1;
    private static OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
            .connectTimeout(CONNECT_TIME_OUT, TimeUnit.MINUTES)
            .writeTimeout(WRITE_TIME_OUT, TimeUnit.MINUTES)
            .readTimeout(READ_TIME_OUT, TimeUnit.MINUTES)
            .build();

    // get请求
    public static void httpGet(String url, Callback callback) throws Exception {
        try {
            Request request = new Request.Builder().url(url).get().build();
            mOkHttpClient.newCall(request).enqueue(callback);
        } catch (Exception e) {
            throw e;
        }
    }

    public static void httpPost(String url, Map<String, String> params, Callback callback) throws Exception {
        try {
            FormBody.Builder formBodyBuilder = new FormBody.Builder();
            if (params == null) {
                params = new HashMap<>();
            }
            /**
             * 在这对添加的参数进行遍历
             */
            for (Map.Entry<String, String> map : params.entrySet()) {
                String key = map.getKey();
                String value;
                /**
                 * 判断值是否是空的
                 */
                if (map.getValue() == null) {
                    value = "";
                } else {
                    value = map.getValue();
                }
                /**
                 * 把key和value添加到formBody中
                 */
                formBodyBuilder.add(key, value);
            }
            RequestBody requestBody = formBodyBuilder.build();
            Request request = new Request.Builder()
                    .post(requestBody)
                    .url(url)
                    .build();
            mOkHttpClient.newCall(request).enqueue(callback);
        } catch (Exception e) {
            throw e;
        }
    }

    // post请求无参
    public static void httpPost(String url, Callback callback) throws Exception {
        try {
            Request request = new Request.Builder().url(url).build();
            mOkHttpClient.newCall(request).enqueue(callback);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    public static String httpPostAnync(String url) throws Exception {
        try {
            Request request = new Request.Builder().url(url).build();
            Response response = mOkHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
            throw e;
        }
        return "";
    }

    // post请求
    public static void httpPost(String url, String json, Callback callback) throws Exception {
        try {
            RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
            Request request = new Request.Builder()
                    .post(body)
                    .url(url)
                    .build();
            mOkHttpClient.newCall(request).enqueue(callback);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    // post请求
    public static String httpPostAsync(String url, String json) throws Exception {
        try {
            RequestBody body = RequestBody.create(MEDIA_TYPE_JSON, json);
            Request request = new Request.Builder()
                    .post(body)
                    .url(url)
                    .build();
            Response response = mOkHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                String result = response.body().string();
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return "";
    }

    /**
     * 基于http的下载文件请求
     *
     * @param downloadUrl 下载地址
     */
    public static void downloadRequest(String downloadUrl, Callback callback) {
        // 创建OKHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(downloadUrl)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);
    }

    public static void cancelAllReuest() {
        if (mOkHttpClient == null) {
            return;
        }
        for (Call call : mOkHttpClient.dispatcher().queuedCalls()) {
            call.cancel();
        }
        for (Call call : mOkHttpClient.dispatcher().runningCalls()) {
            call.cancel();
        }


    }


    /**
     * 基于http的文件上传
     * 通过addFormDataPart可以添加多个上传的文件
     */
    public void uploadMultiFile(File file, Callback callback) {
        // 创建OKHttpClient对象
        OkHttpClient okHttpClient = new OkHttpClient();
//        File file = new File(Environment.getExternalStorageDirectory(), "pic.png");
        RequestBody fileBody = RequestBody.create
                (MediaType.parse("application/octet-stream"), file);
        RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("image", "pic.png", fileBody)
                .build();
        Request request = new Request.Builder()
                .url("填写url地址")
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(callback);
    }


}
